﻿using System;
using System.Collections.Generic;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Connection;
using System.Linq;
using System.Reflection;

namespace NHibernateExample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ISession session = OpenSession())
            {
                ISQLQuery showListsQuery = session.CreateSQLQuery("SHOW LISTS").AddEntity(typeof(Lists));
                IList<Lists> lists = showListsQuery.List<Lists>();

                if (lists.Any())
                {
                    Console.WindowWidth = 90;
                    const string header = "{0,-38} {1,-23} {2,-11} {3}";
                    Console.WriteLine(header, "ID", "Title", "Created", "ItemCount");
                    foreach (Lists list in lists)
                    {
                        Console.WriteLine(header, list.ID, list.Title, list.Created.ToShortDateString(), list.ItemCount);
                    }
                }
                else
                {
                    Console.WriteLine("Could not fetch any lists");
                }

            }
            Console.WriteLine("Done");
            Console.Read();
        }

        static ISessionFactory _sessionFactory;
        static ISession OpenSession()
        {
            if (_sessionFactory == null)
            {
                // Create configuration instance
                var configuration = new Configuration();

                // Fetch the first connectionProvider, if you have several configure them manually and disable this
                var connectionProvider = Assembly.GetExecutingAssembly().GetTypes().First(x => (typeof(IConnectionProvider)).IsAssignableFrom(x));

                if (connectionProvider != null)
                {
                    // Register the connection probider
                    configuration.SetProperty("connection.provider", connectionProvider.AssemblyQualifiedName);
                }

                configuration.AddAssembly(Assembly.GetCallingAssembly());
                _sessionFactory = configuration.BuildSessionFactory();
            }
            return _sessionFactory.OpenSession();
        }
    }
}
